package dao

import (
	"common"
	"context"
	"epai/internal/model"
	"gorm.io/gorm"
)

// AddGoodsCategory 增加一个商品分类
func AddGoodsCategory(ctx context.Context, db *gorm.DB, name string) (*model.GoodsCategory, error) {
	uuidV := common.GenerateXID()
	if name == "推荐" {
		uuidV = "0000"
	}

	goodCategory := &model.GoodsCategory{
		GoodsCategoryId: uuidV,
		Name:            name,
	}
	err := db.WithContext(ctx).Create(&goodCategory).Error
	return goodCategory, err
}

// GetAllGoodsCategory 获取所有商品分类
func GetAllGoodsCategory(ctx context.Context, db *gorm.DB) ([]model.GoodsCategory, error) {
	var goodsCategorys []model.GoodsCategory
	err := db.WithContext(ctx).Model(&model.GoodsCategory{}).Find(&goodsCategorys).Error

	for i, _ := range goodsCategorys {
		if goodsCategorys[i].Name == "推荐" {
			goodsCategorys[i], goodsCategorys[0] = goodsCategorys[0], goodsCategorys[i]
			break
		}
	}
	return goodsCategorys, err
}

// GetAllGoodsCategoryName 获取所有商品分类名字
func GetAllGoodsCategoryName(ctx context.Context, db *gorm.DB) ([]string, error) {
	var result []string
	err := db.WithContext(ctx).Model(&model.GoodsCategory{}).Pluck("name", &result).Error
	if err != nil {
		return nil, err
	}
	return result, err
}

// DelGoodsCategorySlice 批量删除商品分类
func DelGoodsCategorySlice(ctx context.Context, db *gorm.DB, GoodsCategoryName []string) error {
	// 直接开删
	err := db.WithContext(ctx).Where("goods_category_id != ? AND name IN ?", "0000", GoodsCategoryName).Delete(&model.GoodsCategory{}).Error // 错误忽略，后面还要处理
	if err != nil {
		return err
	}
	return err
}
